/*
 * @Author: your name
 * @Date: 2022-04-26 15:55:13
 * @LastEditTime: 2022-04-27 10:31:19
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \vite\src\store\cars.ts
 */
import { defineStore } from 'pinia';
import { shopStore } from './shops';

interface food {
  id: string;
  title: string;
  price: number;
  nums: number;
}

interface cars {
  [index: string]: food;
}
export const carStore = defineStore('car', {
  state: () => {
    return {
      cars: {} as cars,
      price: 0,
    };
  },
  getters: {
    /**
     * 对象转数组 便于展示
     */
    carsList(): Array<food> {
      let cars = [];
      if (!this.cars) {
        return [];
      }
      for (var key in this.cars) {
        if (this.cars.hasOwnProperty(key)) {
          cars.push(this.cars[key]);
        }
      }
      return cars;
    },
    /**
     * 计算总价
     */
    totalPrice() {
      let cars: Array<food> = this.carsList;
      let total = cars.reduce((all, item) => {
        return all + item.price * item.nums;
      }, 0);
      return total;
    },
  },
  //开启持久化
	persist: {
		enabled: true,
		// storage:sessionStorage/localStorage,还可以自定义如下
		// https://seb-l.github.io/pinia-plugin-persist/
		// import Cookies from 'js-cookie'
		// const cookiesStorage: Storage = {
		//   setItem (key, state) {
		//     return Cookies.set('accessToken', state.accessToken, { expires: 3 })
		//   },
		//   getItem (key) {
		//     return JSON.stringify({
		//       accessToken: Cookies.getJSON('accessToken'),
		//     })
		//   },
		// }
		strategies: [
		      { storage: localStorage, paths: ['cars'] }
		    ],
	},
  actions: {
    /**
     * 添加到购物车
     * @param id
     */
    addToCar(id: string) {
      const shop = shopStore();
      // 获取商品
      let foods: cars = shop.getShopObj;
      if (foods[id].nums <= 0) {
        return;
      }
      // 商品数量减少
      shop.joinCard(id);
      // 购物车如果存在商品 数量加1 否则新增
      if (this.cars[id]) {
        this.cars[id].nums++;
      } else {
        // 简单深拷贝
        this.cars[id] = JSON.parse(JSON.stringify(foods[id]));
        this.cars[id].nums = 1;
      }
    },
    /**
     * 从购物车减少
     * @param id
     */
    cudCar(id: string) {
      const shop = shopStore();
      // 如果只剩下一个就移除 否则就减少一个
      if (this.cars[id].nums === 1) {
        Reflect.deleteProperty(this.cars, id);
      } else {
        this.cars[id].nums--;
      }
      // 商品数量加1
      shop.cardToShop(id);
    },
  },
});

